﻿using CommonTools;
using Newtonsoft.Json;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.cost
{
    public class ShopPersonBll : IPageBll<ShopPerson>
    {
        public string Title => "店铺负责人";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Action<int> TurnPage { set; get; }
        public ShopPerson CopyItem(ShopPerson item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.Id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public ShopPerson CreateItem()
        {
            return new ShopPerson() { isdel = false,  };
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<ShopPerson>()
                .Where(a => a.Id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value, ShopPerson data)
        {
            if (data.Id == 0)
            {
                //data.FTime = await DB.FSql.GetTimeAsync();
                //data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.Id = (int)nid;

            }

            var dbRes = await DB.FSql.Update<ShopPerson>()
                .Where(a => a.Id == data.Id && a.isdel == false)
                .SetDto(new Dictionary<string, object> { [dataPropertyName] = value })
                .ExecuteAffrowsAsync();

            return new Result<int>(true, null, data.Id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
           {
                new DeclareColumn(nameof(ShopPerson.Id),"Id"){ Visible= false},
                new DeclareColumn(nameof(ShopPerson.Shop),"店铺"){Width=170},
                new DeclareColumn(nameof(ShopPerson.Name),"店铺负责人"){ Width=130 },
                new DeclareColumn(nameof(ShopPerson.PersonId),"负责ID"){ Width=130 },
                new DeclareColumn(nameof(ShopPerson.StartDate),"上架时间"){ Width=130 },
            };

        }

        public async Task<ShopPerson> GetItem(int id)
        {
            var list = await DB.FSql.Select<ShopPerson>()
                .Where(a => a.isdel == false && a.Id == id)
                .ToOneAsync();
            return list;
        }



        #region 查询参数

        private string _shop;
        private string _name;


        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .AddGuanTextBox("店铺", c => _shop= c)
                .AddGuanTextBox("负责人", c => _name= c)
                .AddQueryButton("查询");
        }


        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<ShopPerson>> QueryPage(DocFilterParameter queryPara)
        {
            var list = await DB.FSql.Select<ShopPerson>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(_shop), a => a.Shop.Contains(_shop))
                .WhereIf(!string.IsNullOrEmpty(_name), a => a.Name.Contains(_name))
                .Page(queryPara.PageNo, queryPara.PageSize)
                .OrderByDescending(a => a.Id)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<ShopPerson>(true, null, list, c);
        }



        public async Task<Result> SaveItem(ShopPerson item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }


            string err = string.Empty;
            if (string.IsNullOrEmpty(item.Shop))
            {
                err += "店铺名称不能为空";
            }

            if (string.IsNullOrEmpty(item.Name))
            {
                err += "负责人不能为空";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;

            if (item.Id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.Id = (int)id;
            }
            else
            {
                await DB.FSql.Update<ShopPerson>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);

        }


        public async Task<Result> SaveItem(IEnumerable<ShopPerson> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }


            foreach (var item in items)
            {
                item.isdel = false;
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();
            //删除重复的
            var cmd = @"UPDATE  ShopPerson SET isdel =1
FROM ShopPerson INNER JOIN (
SELECT a.Shop, a.Name, a.PersonId, MIN(a.Id) mid 
FROM dbo.ShopPerson AS a
where a.isdel =0 
GROUP BY a.Shop, a.Name, a.PersonId
HAVING COUNT(*)>1) AS b ON ShopPerson.id= b.mid
where ShopPerson.isdel=0";

            await DB.FSql.Ado.ExecuteNonQueryAsync(System.Data.CommandType.Text, cmd, null);

            return new Result(true);

        }


    }
}
